# -*- coding: utf8 -*-

import base64
import json
import time
import requests
import os
import random
from od_config import HOST, PORT, TG_URL
import cv2


save_path = r"test_result"
if not os.path.exists(save_path):
    os.makedirs(save_path,exist_ok=True)

image_dir = 'test_imgs'  
img_list = os.listdir(image_dir)
for i in img_list:
    out_img = cv2.imread(os.path.join(image_dir,i))
    img_panel = open(image_dir + '/' + i, "rb").read()
    panel_file = base64.b64encode(img_panel)
    ls = [
            {
                "image": str(panel_file, encoding="utf-8"),
                "minScore":0.5,
            }
	]
    for postdata in ls:
        values_json = json.dumps(postdata, ensure_ascii=False)
        start_time = time.time()
        address = 'http://' + HOST + ':' + str(PORT) + TG_URL
        #address = 'http://172.17.0.3:8637/api/v1/windows-plugging'
        r = requests.post(address, data=values_json)
        end_time = time.time()
        print('**************** ' + i + ' ****************')
        print(i)
        print(f"耗用时间:{end_time - start_time}")
        print(json.dumps(r.json(), indent=4, ensure_ascii=False))
        #print(r.json())
        message = r.json()['message']
        if len(r.json()['marks']) >0:
            for out_axis in r.json()['marks']:
            	c = out_axis['axis']
            	x1 = int(c[0])
            	y1 = int(c[1])
            	x2 = int(c[2])
            	y2 = int(c[3])
            	cv2.rectangle(out_img, (x1, y1), (x2, y2), [0, 0, 255], 2)   # 画出所有检测框
            	cv2.putText(out_img, f"{out_axis['cls']} {out_axis['score']}", (x1, y1 - 5),
                	        cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3)
            	cv2.putText(out_img, message, (60,60),cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 3)
        else:
                cv2.putText(out_img, message, (60,60),cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 3)
        # cv2.imwrite(os.path.join(save_path,i), out_img)


